<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use app\index\model\Category as categoryModel;
class Category extends Controller
{
	// 查询
	public function query(){
		$categorys = self::getTree(0);
		return json($categorys);
	}
	public function getTree($pid){
		$categorys = categoryModel::where("pid",$pid)->select();
		foreach($categorys as $category){
			$category->children = self::getTree($category->id);
		}
		return $categorys;
	}
	public function getByPid(){
		$pid = input('get.pid');
		$categorys = categoryModel::where("pid",$pid)->select();
		return json(["code"=>200,"data"=>$categorys]);
	}
	public function save(){
		$pid = input('post.pid');
		$name = input('post.name');
		$category = new categoryModel();
		$category->pid = $pid;
		$category->name = $name;
		$category->save();
	}
	public function update(){
		$id = input('post.id');
		$pid = input('post.pid');
		$name = input('post.name');
		$category = categoryModel::get($id);
		if($pid){
			$category->pid = $pid;
		}
		if($name){
			$category->name = $name;
		}
		$category->save();
	}
	public function delete(){
		$id = input('get.id');
		$category = categoryModel::get($id);
		$category->delete();
	}
}
